import { Component, OnInit } from '@angular/core';
import { TScenario } from '../../types';
import {
  UntypedFormBuilder,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';
import { ScenarioService } from 'src/app/share/service/scenario.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { RESPONSE_DATA } from 'src/app/share/const/interfaces';
import { RESPONSE_CODE } from 'src/app/share/const/base.const';

@Component({
  selector: 'app-scenario-table',
  templateUrl: './scenario-table.component.html',
  styleUrls: ['./scenario-table.component.less'],
})
export class ScenarioTableComponent implements OnInit {
  constructor(
    private service: ScenarioService,
    private message: NzMessageService
  ) {}
  ngOnInit(): void {
    this.queryTableData();
  }
  //编辑缓存数据
  editCache: { [key: number]: { edit: boolean; data: TScenario } } = {};
  tableData: TScenario[] = [];
  tableLoading = false;
  //编辑时候的form数组
  editForms: UntypedFormGroup[] = [];

  page = 1;
  pageSize = 10;
  total = 0;

  // 查询scenarios的数据
  queryTableData() {
    this.tableLoading = true;
    this.service
      .queryAllScenariosByPage(this.page, this.pageSize)
      .subscribe((res) => {
        const { code, data, total } = res as RESPONSE_DATA<TScenario[]>;
        if (code === RESPONSE_CODE.SUCCESS) {
          if (total) {
            this.total = total;
          }
          data.map((d, idx) => {
            data[idx]['sort'] = idx + 1;
          });
          this.tableData = data;
          // 更新编辑缓存和form列表以供备用
          this.updateEditCache();
          // this.updateEditForms();
          this.tableLoading = false;
        }
      });
  }

  onAddComplete(value: any) {
    // 创建scenario成功
    this.queryTableData();
  }

  onQueryParamsChange(value: any) {
    // page已通过双向绑定修改过了
    this.queryTableData();
  }

  // 确定删除
  handleDelete(id: number) {
    this.service.deleteScenario(id).subscribe((res) => {
      const { code, msg } = res as RESPONSE_DATA;
      if (code == RESPONSE_CODE.SUCCESS) {
        this.message.success('删除成功');
        this.queryTableData();
      } else {
        this.message.error(msg);
      }
    });
  }

  // 开始编辑
  startEdit(id: number): void {
    this.editCache[id].edit = true;
  }
  //更新编辑缓存
  updateEditCache(): void {
    this.tableData.forEach((item) => {
      this.editCache[item.id] = {
        edit: false,
        data: { ...item },
      };
    });
  }

  // 取消编辑
  cancelEdit(id: number): void {
    const index = this.tableData.findIndex((item) => item.id === id);
    const data = this.tableData[index];
    this.editCache[id] = {
      data: { ...data },
      edit: false,
    };
  }

  // 保存数据
  saveEdit(data: TScenario): void {
    const { id, scenario, description } = this.editCache[data.id].data;
    this.service
      .updateScenario(id, {
        scenario,
        description,
      })
      .subscribe((res) => {
        const { code, msg } = res as RESPONSE_DATA;
        if (code == RESPONSE_CODE.SUCCESS) {
          this.message.success('修改成功');
          // 更新表格数据
          const index = this.tableData.findIndex((item) => item.id == id);
          Object.assign(this.tableData[index], this.editCache[id].data);
          this.editCache[id]['edit'] = false;
        } else {
          this.message.error(msg);
        }
      });
  }

  // copy
  handleCopy(data: TScenario) {
    this.service.copyScenario(data.id).subscribe((res) => {
      const { code } = res as RESPONSE_DATA;
      if (code === RESPONSE_CODE.SUCCESS) {
        this.message.success('复制成功');
        this.queryTableData();
      }
    });
  }
}
